package org.devio.secondlevelmenu.spinner;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.devio.secondlevelmenu.R;

/**
 * Created by amazingZZ on 11/25/21
 */
    public class CustomSpinner extends RelativeLayout implements NormalSpinnerAdapter.AdapterItemClick {

    private View root;

    private TextView spinner_tv;
    private ImageView imgRight;
    private RelativeLayout spinner_tv_vp;
    private SpinnerPopupWindow mSpinerPopWindow;
    private String[] strArr;


    public CustomSpinner(Context context) {
        super(context);
        init();
    }


    public CustomSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }


    private void init() {
        root = LayoutInflater.from(getContext()).inflate(R.layout.custom_spanner, this, true);
        spinner_tv = (TextView) findViewById(R.id.spinner_tv);
        spinner_tv_vp = (RelativeLayout) findViewById(R.id.spinner_tv_vp);
        imgRight = (ImageView) findViewById(R.id.img);
        spinner_tv_vp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSpinerPopWindow.setWidth(spinner_tv_vp.getWidth());
                setRightDrawable(R.drawable.ic_pack_up);
                mSpinerPopWindow.showAsDropDown(spinner_tv_vp);

            }
        });
        setRightDrawable(R.drawable.ic_pack_down);

    }

    public void setStrArr(String[] strArr) {
        if (strArr != null && strArr.length > 0) {
            this.strArr = strArr;
            spinner_tv.setText(strArr[0]);
            mSpinerPopWindow = new SpinnerPopupWindow(getContext(), this);
            mSpinerPopWindow.addData(strArr);
        }
    }

    private void setRightDrawable(int res) {
        imgRight.setImageResource(res);
    }

    @Override
    public void itemClick(int position, String string_content) {
        setRightDrawable(R.drawable.ic_pack_down);
        spinner_tv.setText(string_content);
        mSpinerPopWindow.dismiss();
        if (itemSelectedListener != null)
            itemSelectedListener.onItemSelected(position, string_content);
    }

    private OnItemSelectedListener itemSelectedListener;

    public void setItemSelectedListener(OnItemSelectedListener itemSelectedListener) {
        this.itemSelectedListener = itemSelectedListener;
        itemSelectedListener.onItemSelected(0,strArr[0]);
    }

    public interface OnItemSelectedListener {
        void onItemSelected(int position, String content);

    }
}
